package com.nd.android.u.ui.widge.chatfragment;

import ims.utils.CommUtil;
import ims.utils.IMLogUtils;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout;

import com.common.allCommon.CommonUtils;
import com.common.allCommon.PackUtils;
import com.common.android.utils.task.genericTask.GenericTask;
import com.common.android.utils.task.genericTask.TaskAdapter;
import com.common.android.utils.task.genericTask.TaskListener;
import com.common.android.utils.task.genericTask.TaskParams;
import com.common.android.utils.task.genericTask.TaskResult;
import com.nd.android.u.allCommonUtils.ToastUtils;
import com.nd.android.u.chatInterfaceImpl.ChatInterfaceImpl;
import com.nd.android.u.chatUtil.ReflectUtil;
import com.nd.android.u.commonWidget.NotificationMsg;
import com.nd.android.u.controller.ChatConst.LocalMessageType;
import com.nd.android.u.controller.ChatConst.MessageContentType;
import com.nd.android.u.controller.ChatGlobalVariable;
import com.nd.android.u.controller.MessageConst.ChatNotify;
import com.nd.android.u.controller.MessageConst.MessageCommonState;
import com.nd.android.u.controller.MessageConst.MessageState;
import com.nd.android.u.controller.bean.ImageMessage;
import com.nd.android.u.controller.factory.ChatDaoFactory;
import com.nd.android.u.controller.factory.MessageLongClickMenuFactory;
import com.nd.android.u.controller.innerInterface.IChatListItem;
import com.nd.android.u.controller.innerInterface.IMessageDisplay;
import com.nd.android.u.controller.innerInterface.IMessageObserver;
import com.nd.android.u.controller.innerInterface.IUIDataSupplier;
import com.nd.android.u.controller.observer.MessageDispatcher;
import com.nd.android.u.ui.R;
import com.nd.android.u.ui.activity.message_chat.MessageAdapter;
import com.nd.android.u.ui.chatUiUtils.AudioQuenePlayManager;
import com.nd.android.u.ui.chatUiUtils.SendMessageUtil;
import com.nd.android.u.ui.widge.PopNewMessage;
import com.nd.android.u.ui.widge.ScrollListView;
import com.nd.android.u.ui.widge.ScrollListView.OnRefreshListener;
import com.nd.android.u.ui.widge.ScrollListView.PullDownListener;
import com.nd.android.u.ui.widge.lift.Lift;
import com.product.android.business.manager.MotionEventManager;

/**
 * 聊天界面中间显示消息的列表 <br>
 * Created 2014-5-5 下午11:57:17
 * 
 * @version
 * @author cb
 * @see
 */
@SuppressLint("ValidFragment")
public class MessageListFragment extends RelativeLayout{
    public static final int PAGESIZE = 10;
    public static final int OP_SEND = 1; // 发送

    /** 消息内容 */
    protected ScrollListView mListView;
    protected MessageAdapter mChatAdapter;
    protected List<IMessageDisplay> mMessageList = new ArrayList<IMessageDisplay>();
    // protected PspMessageListview mMessageListview;
    /** listView父控件 */
    protected RelativeLayout mChatListViewLayout;
    /** 下接刷新列表线程取资料 */
    protected GenericTask mRefreshTask;

    /** 通过接口与其它通讯 */
    private MessageListListener mMessageListCallBack;

    /** 当前的联系人类型，见localMessageType */
    private int mMessageType;

    /** 数据接口 */
    private IUIDataSupplier mDataSupplier;

    /** 底部小的未读消息控件 */
    private PopNewMessage mPopMessage;
    /** 是否掉蛋糕 */
    private boolean mbIsLiftAvailable = true;
    /** 掉蛋糕的控件 */
    private Lift mLift;
    /** 连续播放音频控制类 */
    private AudioQuenePlayManager mQuenePlayManager;
    /** 是否要显示未读消息数（弹窗界面不显示）*/
    private boolean mDontShowPopMessage=false;
    

	private View mFootOffsetView;
	
    /**
     * 消息列表接口
     * <br>Created 2014-9-12 上午11:41:03
     * @version  MessageListFragmentCommon
     * @author   cb		
     * @see 	 
     */
    public interface MessageListListener {
        /** 隐藏fragment */
        void onDismissOtherFragment();
    }
    
    private Activity mActivity;
    /**
     * 屏蔽掉蛋糕动画 <br>
     * Created 2014-5-5 下午11:45:41
     * @author cb
     */
    public void disableLift() {
        mbIsLiftAvailable = false;
    }
    
    /**
     * 设置列表监听接口
     * <br>Created 2014-9-20 上午11:42:59
     * @param listener 列表监听接口
     * @author  cb
    */
    public void setMessageListListener(MessageListListener listener){
    	mMessageListCallBack=listener;
    }
    
    /**
     * 设置数据提供者
     * <br>Created 2014-9-20 上午11:42:53
     * @param supplier 数据提供者
     * @author  cb
    */
    public void setDataSupplier(IUIDataSupplier supplier){
    	mDataSupplier=supplier;
    }
    
    /**
     * 设置消息类型
     * <br>Created 2014-9-20 上午11:42:46
     * @param type 消息类型
     * @author  cb
    */
    public void setMessageType(int type){
    	mMessageType=type;
    	MessageDispatcher.getInstance().registObserver(mMessageType, mObserver);
        int[] subTypes=ChatInterfaceImpl.INSTANCE.getSubTypes(mMessageType);
		if (subTypes!=null){
			for (int i : subTypes) {
				MessageDispatcher.getInstance().registObserver(i, mObserver);
			}
		}
		showMessages();
    }
    
    /**
     * 设置是否显示新消息数量（弹窗界面不显示）
     * <br>Created 2014-9-20 上午11:43:13
     * @param show true表示要显示
     * @author  cb
    */
    public void setIsShowPopMessage(boolean show){
		mDontShowPopMessage=!show;
    }
    
    /**
     * 设置转发的消息ID
     * <br>Created 2014-9-20 上午11:44:07
     * @param repostMsgId 转发的消息ID
     * @author  cb
    */
    public void setRepostId(String repostMsgId){
		if (!TextUtils.isEmpty(repostMsgId)) {
			SendMessageUtil.repost(repostMsgId,mDataSupplier);
		}
    }

    
    /**
     * MessageListFragment.构造方法
     * <br>Created 2014-9-20 上午11:46:47
     * @param context 上下文
     */
    public MessageListFragment(Activity context) {
    	super(context);
    	mActivity=context;
    	initView();
    }
    
    /**
     * 解注册观察
     * <br>Created 2014-9-12 上午11:44:11
     * @author  cb
    */
    private void unregistObserver(){
    	MessageDispatcher.getInstance().unregistObserver(mMessageType, mObserver);
		int[] subTypes=ChatInterfaceImpl.INSTANCE.getSubTypes(mMessageType);
		if (subTypes!=null){
			for (int i : subTypes) {
				MessageDispatcher.getInstance().unregistObserver(i, mObserver);
			}
		}
    }

    /**
     * 初始化控件 <br>
     * Created 2014-5-5 下午11:56:53
     * @author cb
     */
    protected void initView() {
    	LayoutInflater.from(mActivity).inflate(R.layout.chat_pub_messagelist_fragment, this, true);
        mListView = (ScrollListView) findViewById(R.id.lv_chat);
        mListView.setCacheColorHint(0);
        mListView.setDivider(null);
        initOffsetFootView();
        mChatAdapter = new MessageAdapter(mActivity);
        mListView.setAdapter(mChatAdapter);
        mChatListViewLayout = (RelativeLayout) findViewById(R.id.chat_listview_layout);
        mLift = new Lift(mActivity, mChatListViewLayout);
        mQuenePlayManager = AudioQuenePlayManager.getInstance();
        mQuenePlayManager.setDetailList(mMessageList);
        initEvent();
    }
    
    /**
     * 初始化底部用于达到间距效果的布局
     * 
     * <br>Created 2014-10-20 下午5:01:40
     * @author        :  HuangYK
     */
    private void initOffsetFootView() {
    	if(mFootOffsetView==null){
    		mFootOffsetView = new View(mActivity); 
    		mFootOffsetView.setLayoutParams(new AbsListView.LayoutParams(
    				LayoutParams.MATCH_PARENT, CommonUtils.dipToPx(mActivity, 55)));
    	}
		mListView.removeFooterView(mFootOffsetView);
		mListView.addFooterView(mFootOffsetView);
		mListView.postInvalidate();
	}

    /**
     * 初始化事件 <br>
     * Created 2014-5-5 下午11:57:04
     * 
     * @author cb
     */
    private void initEvent() {
        // 下拉刷新
        mListView.setonRefreshListener(new OnRefreshListener() {
            public void onRefresh() {
                refreshList();
            }
        });
        mListView.setOnScrollListener(onScrollListener);
        mListView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (null != mMessageListCallBack) {
					mMessageListCallBack.onDismissOtherFragment();
				}
				return false;
			}
		});
        if (mMessageType==LocalMessageType.PERSON){
        	//只有个人聊天才有送花的控件
        	mListView.setPullDownListener(new PullDownListener() {
                @Override
                public void pullDown(float distance) {
                	Message msg=new Message();
                	msg.arg1=(int) distance;
                	msg.what=ChatNotify.SHOW_FLOWER_WIDGET;
                	//通知送花控件界面被拖动（基于需求：聊天界面送花按钮隐藏起来后，当用户向下划动界面，且划动的距离大于送花的按钮的高度且小于4*送花的按钮的高度时，需要再次显示送花控件）
                	MessageDispatcher.getInstance().notifyOtherMessage(mMessageType, msg);
                }
            });
        }
        new EventManager(mListView);
        if (mMessageType==LocalMessageType.SYSTEM ||
        	mMessageType==LocalMessageType.APP){
        	//应用消息的系统消息的点击事件是通用的
        	mListView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					if (position==0){
						return;
					}
					IMessageDisplay display=mMessageList.get(position-1);
					display.onItemClick(mActivity);
				}
			});
        }
    }

    /**
     * 刷新指定的控件 <br>
     * Created 2014-5-7 下午3:16:57
     * @param message 消息
     * @author cb
     */
    private void refreshSpecifiedView(IMessageDisplay message) {
        // 仅刷新指定的view
        int count = mListView.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = mListView.getChildAt(i);
            if (view instanceof IChatListItem) {
                IMessageDisplay now = ((IChatListItem) view).getData();
                if (now.equals(message)) {
                    ReflectUtil.copy(message, now);
                    ((IChatListItem) view).setData(now);
                    return;
                }
            }
        }
        // 如果上面的处理中未能刷新，说明不是当前显示的item无需刷新
    }

    /**
     * 下拉分页查询聊天记录 <br>
     * Created 2014-5-5 下午11:58:02
     * 
     * @author cb
     */
    @TargetApi(Build.VERSION_CODES.CUPCAKE)
	public void refreshList() {
        if (mMessageList == null) {
            Log.d("debug", "null messagelist in " + this.getClass().getName());
            return;
        }
        if (mRefreshTask != null && mRefreshTask.getStatus() == GenericTask.Status.RUNNING) {
            return;
        } else {
            mRefreshTask = new RefreshListTask();
            mRefreshTask.setListener(mTaskListener);
            TaskParams params = new TaskParams();
            mRefreshTask.execute(params);
        }
    }

    /**
     * 
     * ClassName:RefreshListTask Function: TODO 开个线程从数据库取出更多内容 Reason: TODO ADD REASON
     * @author zhy
     * @since Ver 1.1
     * @Date 2014 2014-4-30 下午4:41:39
     * @see
     */
    private class RefreshListTask extends GenericTask {
        @Override
        public TaskResult _doInBackground(TaskParams... params) {
            long msgid = mDataSupplier.getFirstMessageId();
            if (msgid > 0) {
                paraData = mDataSupplier.getData(msgid, PAGESIZE);
                return TaskResult.OK;
            }
            return TaskResult.FAILED;
        }
    }

    private TaskListener mTaskListener = new TaskAdapter() {
        @Override
        public void onPostExecute(GenericTask task, TaskResult result) {
            if (result == TaskResult.OK) {
                if (task.paraData != null) {
                    if (task.paraData instanceof ArrayList<?>) {
                        @SuppressWarnings("unchecked")
                        ArrayList<IMessageDisplay> moreDatas = (ArrayList<IMessageDisplay>) task.paraData;
                        mMessageList.addAll(0, moreDatas);
                        mChatAdapter.setList(mMessageList);
//                        mChatAdapter.notifyDataSetChanged();
                        mListView.setSelection(moreDatas.size());
                    }
                }
            }
            mListView.onRefreshComplete();
        }
    };
    
    /**
     * 显示消息
     * <br>Created 2014-7-21 下午3:36:30
     * @author       mengnan
    */
    private void showMessages() {
        // 新消息的数量（包括在其它登录点自己发的）
        int newMessageCount = mDataSupplier.getNewMessageCount();
        // 未读消息的数量（只含别人发的）
        int unreadMessageCount = mDataSupplier.getUnreadMessageCount();
        if (unreadMessageCount > 0) {
            mDataSupplier.clearUnreadCount();
        }
        // 取数据库里的数据
        mMessageList.clear();
        mMessageList.addAll(mDataSupplier.getData(-1, PAGESIZE));
        mChatAdapter.setList(mMessageList);
        // sendRepostMessage();
//        mChatAdapter.notifyDataSetChanged();
        NotificationMsg.getInstance().callbackSetNotiType();
        mListView.setSelection(mMessageList.size() - newMessageCount);
        // 下面这段蛋疼的处理是为了解决在转发的聊天界面再点击通知栏里新消息进入另一个聊天界面时，界面的数据不会立即刷新的问题
        // 但是一时没别的办法来解决这个问题。另一个方案是把sinle_top换成standard或者是single_task，但是这样改动的影响比较大
        // 有没有人能把这个问题搞定的？
        mListView.setVisibility(View.GONE);
        // TAG zhy
        // tvState.requestFocus();
        new Handler().postDelayed(new Runnable() {
            public void run() {
                mChatAdapter.notifyDataSetChanged();
                mListView.setVisibility(View.VISIBLE);
            }
        }, 1);
    }

    private OnScrollListener onScrollListener = new OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                int totalItemCount) {
            if (mPopMessage != null && mPopMessage.isShowing()) {
                // Log.d("debug",
                // "firstVisibleItem="+firstVisibleItem+",visibleItemCount="+visibleItemCount+",totalItemCount="+totalItemCount+",size="+mDetailList.size()+",now count="+mPopMessage.getCount());
                int lastItem = mListView.getFirstVisiblePosition() + visibleItemCount;
                if (lastItem + mPopMessage.getCount() > totalItemCount) {
                    // 滚动到第一条未查看 的消息的时，隐藏提醒
                    mPopMessage.dismiss();
                }
            }
        }
    };

    /**
     * 展示消息 <br>
     * Created 2014-5-5 下午11:38:52
     * 
     * @param message
     *            要展示的消息
     * @param isFromLocal
     *            消息是否是本机发的
     * @author cb
     */
    private void showMessage(IMessageDisplay message, boolean isFromLocal) {
        if (message == null) {
            return;
        }
        if (mActivity.isFinishing()) {
            return;
        }
        if (mListView.getLastVisiblePosition() < mMessageList.size() - 1 && !isFromLocal
                && mListView instanceof ScrollListView) {
            // 在底部显示新消息数量的小圆圈
            // 显示条件：1.界面内可视的最后一条消息不是整个列表里的最后一条 2.是别人发的消息 3.在应用内的聊天界面（不是弹窗）
        	if (PackUtils.isTopActivity(mActivity.getClass()) && !mDontShowPopMessage){
        		if (mPopMessage == null) {
                    mPopMessage = new PopNewMessage(mActivity);
                    mPopMessage.setOnTextClickListener(onTextClick);
                }
                mPopMessage.show();	
            }
            mChatAdapter.notifyDataSetChanged();
        } else {
            mChatAdapter.notifyDataSetChanged();
            mListView.setSelection(mMessageList.size());

        }
        // 掉蛋糕
        if (!TextUtils.isEmpty(message.getDisplayContent())) {
            selectLift(message.getDisplayContent());
        }
    }

    /**
     * 选择礼物模式（蛋糕/鲜花），并展示动画
     */
    public void selectLift(String message) {
        if (mActivity == null || mActivity.isFinishing()) {
            return;
        }
        String LastMessage = message.replaceAll(" ", "").toLowerCase();
        String[] cakeKeys = mActivity.getResources().getStringArray(R.array.cake_keys);
        int lastCakeIndex = getLastIndexForStrings(LastMessage, cakeKeys); // 消息中最后一个蛋糕key所在位置

        String[] flowerKeys = mActivity.getResources().getStringArray(R.array.flower_keys);
        int lastflowerIndex = getLastIndexForStrings(LastMessage, flowerKeys); // 消息中最后一个鲜花key所在位置

        if (lastCakeIndex == lastflowerIndex) {
            return;
        }
        if (mbIsLiftAvailable) {
            if (lastCakeIndex > lastflowerIndex) { // 当蛋糕key比鲜花key靠后时，屏幕掉蛋糕
                mLift.fallLift(false);
            } else {
                mLift.fallLift(true);
            }
        }
    }

    /**
     * field:onTextClick Function: 点击右下角小圆圈提醒图标后跳到第一条未读消息，并隐藏该图标
     * 
     * @author cb
     * @since Ver 1.2
     * @Date 2013 2013-7-15 下午2:53:54
     */
    private OnClickListener onTextClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            int last = mMessageList.size() - mPopMessage.getCount();
            if (last < 0) {
                last = 0;
            }
            mListView.setSelection(last);
            mPopMessage.dismiss();
        }
    };
	protected IMessageDisplay meessage;

    /**
     * 
     * <br>Created 2014-7-21 下午3:36:56
     * @param message
     * @author       mengnan
    */
    public void resend(IMessageDisplay message) {
        // 重发的时候先删除原消息
        mMessageList.remove(message);
        mChatAdapter.setList(mMessageList);
//        mChatAdapter.notifyDataSetChanged();
        message.resend();
        showMessage(message, true);
    }

    /**
     * 找出字符串中多个key所在位置，并返回最后一个位子 <br>
     * Created 2014-5-6 上午12:15:09
     * 
     * @param src
     * @param keys
     * @return
     * @author cb
     */
    private int getLastIndexForStrings(String src, String[] keys) {
        int lastIndex = -1;
        for (String key : keys) {
            lastIndex = Math.max(src.lastIndexOf(key), lastIndex);
        }
        return lastIndex;
    }

    /**
     * 触点管理 <br>
     * Created 2014-5-6 上午12:14:55
     * 
     * @version MessageListFragment
     * @author cb
     * 
     * @see
     */

    private class EventManager extends MotionEventManager {
        public EventManager(View view) {
            super(view);
        }

        @Override
        protected boolean onZoom(float scale, float source) {
            zoom(scale, source);
            return true;
        }

        @Override
        protected boolean onMove(float startX, float nowX, float startY, float nowY) {
            if (null != mMessageListCallBack) {
                mMessageListCallBack.onDismissOtherFragment();
            }
            return super.onMove(startX, nowX, startY, nowY);

        }

        @Override
        protected boolean onDoubleTouchTown() {
            setSourceComputeValue(ChatGlobalVariable.getInstance().getChatTextSize());
            return false;
        }
        
        @Override
        protected boolean onClick() {
        	if (mMessageType==LocalMessageType.SYSTEM){
        	}
        	return super.onClick();
        }

        @Override
        protected boolean onLongClick(float x, float y) {
            int pos = getPos(x, y);
            if (mMessageList != null && pos < mMessageList.size() && pos >= 0) {
                IMessageDisplay message = mMessageList.get(pos);
                MessageLongClickMenuFactory.getInstance().show(mActivity,message);
            }
            return true;
        };

        /**
         * 根据点击的坐标获取对应的ITEM <br>
         * Created 2014-5-6 上午12:01:41
         * 
         * @param x
         * @param y
         * @return
         * @author cb
         */
        private int getPos(float x, float y) {
            int offset = 0;
            if (mListView instanceof ScrollListView) {
                // scrolllistview有一个headview，所以要减1
                offset = 1;
            }
            int pos = mListView.pointToPosition((int) x, (int) y) - offset;
            return pos;
        }

        /**
         * 缩放 <br>
         * Created 2014-5-6 上午12:12:08
         * 
         * @param scale
         * @param source
         * @author cb
         */
        private void zoom(float scale, float source) {
            float size = scale * source;
            ChatGlobalVariable.getInstance().setChatTextSize(size);
            mChatAdapter.notifyDataSetChanged();
        }
    };

    // mObserver:消息观察者
    private IMessageObserver mObserver = new IMessageObserver() {
        @Override
        public void onReceiveMessage(final IMessageDisplay message) {
        	handlerMessage(message, MessageState.RECEIVED);
        }

        @Override
        public void onOtherMessageNotify(Message message) {
        	if (message==null){
        		return;
        	}
        	if (message.what==ChatNotify.UNSUB_PSP){
        		//目前只处理取消关注公众号的事件
        		Message msg = refreshHandler.obtainMessage();
                msg.what = message.what;
                msg.obj = message.obj;
                refreshHandler.sendMessage(msg);
                return;
        	}
        	if (message.what==ChatNotify.REFRESH_PIC){
        		int size=mMessageList.size();
				if (size==0){
					return;
				}
        		if (message.getData()==null){
        			return;
        		}
    			String key=message.getData().getString("fileKey");
    			if (TextUtils.isEmpty(key)){
    				return;
    			}
				for (int i=size-1;i>0;i--){
					IMessageDisplay disp=mMessageList.get(i);
					for (Object obj : disp.getDisplayDatas()) {
						if (obj instanceof ImageMessage){
							if (((ImageMessage) obj).getImgurl().equals(key)){
								Message msg = refreshHandler.obtainMessage();
				                msg.what = message.what;
				                msg.obj = disp;
				                refreshHandler.sendMessage(msg);
				                message=null;
				                return;
							}
						}
					}
				}
        	}
        	if (message.what==ChatNotify.GROUP_DEL){
        		//群组被删除
        		Message msg = refreshHandler.obtainMessage();
                msg.what = message.what;
                msg.obj = message.obj;
                msg.arg1=message.arg1;
                refreshHandler.sendMessage(msg);
                return;
        	}
        }

        @Override
        public void onSendNewMessage(final IMessageDisplay message) {
            handlerMessage(message, MessageState.SEND_NEW);
        }

        @Override
        public void onMessageStateChanged(IMessageDisplay message, int state) {
            handlerMessage(message, state);
        }
        
        /**
         * 通知handler通知界面刷新
         * <br>Created 2014-7-28 下午10:24:18
         * @param message
         * @param state
         * @author  cb
        */
        private void handlerMessage(IMessageDisplay message, int state){
        	if (!mDataSupplier.isValidMessage(message)) {
                return;
            }
            Message msg = refreshHandler.obtainMessage();
            msg.what = state;
            msg.obj = message;
            refreshHandler.sendMessage(msg);
        }
    };
    
    private Handler refreshHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.obj instanceof IMessageDisplay){
            	proccessChatMessage(msg);
            }else{
            	proccessOtherMessage(msg);
            }
        };
    };
    
    /**
     * 处理聊天消息
     * <br>Created 2014-10-27 下午8:26:09
     * @param msg 消息
     * @author  cb
    */
    private void proccessChatMessage(Message msg){
    	IMessageDisplay message = (IMessageDisplay) msg.obj;
        switch (msg.what) {
        case MessageState.RECEIVED:
        case MessageState.SEND_NEW:
        	if (addMessage(message)){
        		if (!message.isFromSelf()){
            		mDataSupplier.clearUnreadCount();
            		message.getProccessInterface().ackMessage();
            	}
            	showMessage(message, msg.what==MessageState.SEND_NEW);
        	}
        	break;
        case MessageState.DELETED:
            removeMessage(message);
            mChatAdapter.setList(mMessageList);
            mChatAdapter.notifyDataSetChanged();
            break;
        case MessageState.DELETEDALL:
            mMessageList.clear();
            mChatAdapter.setList(mMessageList);
            mChatAdapter.notifyDataSetChanged();
            break;
        case MessageState.ERP_UPDATE:
        	for (IMessageDisplay listItem : mMessageList) {
    			if (listItem.equals(message)){
    				ReflectUtil.copy(message, listItem);
    				refreshSpecifiedView(listItem);
    				return;
    			}
    		}
        	break;
		case ChatNotify.SHOW_LIFT_FLOWER:
			message.setIsRead(MessageCommonState.DONE, true);
			mLift.fallLift(true);
			break;
		case ChatNotify.SHOW_LIFT_CAKE:
			message.setIsRead(MessageCommonState.DONE, true);
			mLift.fallLift(false);
			break;
        default:
        	if (msg.what == MessageState.UPLOAD_FAIL || msg.what == MessageState.DOWNLOAD_FAIL){
        		//如果是上传或者下载失败的，判断一下是否要显示弹窗提醒
        		String err=message.getErrorMsg();
        		if (!TextUtils.isEmpty(err)){
        			ToastUtils.display(err);
        		}
        	}
        	refreshSpecifiedView(message);
            break;
        }
    }
    
    /**
     * 处理其它消息通知
     * <br>Created 2014-10-27 下午8:26:20
     * @param msg 消息
     * @author  cb
    */
    private void proccessOtherMessage(Message msg){
    	switch (msg.what) {
		case ChatNotify.UNSUB_PSP:
			break;
		case ChatNotify.GROUP_DEL:
			leaveGroup(msg);
			break;
		default:
			break;
		}
    }
    
    /**
     * 离开群：可能被T，也可以是自己离开，也可能是群被解散
     * modify tag 2014102302:BUG #56865 【聊天页面】A用户在聊天离线，B解散群，A上线，收到解散的系统消息，但群还在列表
     * <br>Created 2014-10-27 下午8:31:07
     * @param msg
     * @author  cb
    */
    private void leaveGroup(Message msg){
    	/**modify tag 2014102701 by cb:BUG #56826::【通讯录-退出群】A退出群后，回到设置页面 
       	 * 此处的修改是为了避免某些地方传过来的GID是long型的导致类型强转出错*/
       	String gid=msg.obj.toString();
       	long lGid=CommUtil.parseLong(gid);
       	if (lGid!=mDataSupplier.getId()){
       		//删除的不是当前的群
       		return;
       	}
       	//当前群被删除，结束当前界面
       	if (mActivity != null && !mActivity.isFinishing()) {
			mActivity.finish();
		}
    }
    
    /**
     * 把新的消息添加到列表中 <br>
     * Created 2014-5-22 下午5:33:15
     * 
     * @param message
     *            新的消息
     * @author cb
     */
    private boolean addMessage(IMessageDisplay message) {
    	if (mMessageList.contains(message)){
    		int type=message.getMessageContentType();
    		if (message.getIShareFileOperation().isGroup() && message.isFromSelf() && 
    			(type==MessageContentType.FILE || type==MessageContentType.OLD_FILE)){
    			IMLogUtils.e(IMLogUtils.CHAT,"group share file exist:"+message.getFileName());
    			ChatDaoFactory.getInstance().get(LocalMessageType.GROUP).delete(message.getDbOperationSupport());
    		}
    		return false;
    	}
        if (mMessageList.isEmpty()) {
            // 旧的列表是空的，设置时间并添加
            message.setTimeString(0);
            mMessageList.add(message);
        } else {
            int size = mMessageList.size();
            for (int i = size - 1; i >= 0; i--) {
                IMessageDisplay old = mMessageList.get(i);
                if (TextUtils.isEmpty(old.getTimeString())) {
                    // 该消息无时间显示，继续往上找
                    continue;
                } else {
                    // 找到第一个时间不为空的消息，与当前消息进行比较确定当前消息是否要显示时间
                    long time = old.getCreateDate();
                    message.setTimeString(time);
                    break;
                }
            }
            mMessageList.add(message);
        }
        mChatAdapter.setList(mMessageList);
        return true;
    }
    
    /**
     * 从队列里移除消息 <br>
     * Created 2014-5-22 下午5:37:05
     * 
     * @param message
     * @author cb
     */
    private void removeMessage(IMessageDisplay message) {
        int index = mMessageList.indexOf(message);
        if (index != mMessageList.size() - 1 && !TextUtils.isEmpty(message.getTimeString())) {
            // 该消息不是最后一条消息且显示了时间，要把它后面一条消息的时间显示出来
            mMessageList.get(index + 1).setTimeString(0);
        }
        mMessageList.remove(message);
        mChatAdapter.setList(mMessageList);
        // mTotalMessage--;
    }

    /**
     * 刷新列表 <br>
     * Created 2014-5-13 下午3:15:07
     * 
     * @author cb
     */
    public void refreshAdatper() {
        mChatAdapter.notifyDataSetChanged();
    }
    
    /**
     * 获取列表里的数据
     * <br>Created 2014-7-27 下午4:55:36
     * @return 列表里的数据
     * @author       cb
    */
    public List<IMessageDisplay> getData(){
    	return mMessageList;
    }
    
    /**
     * 清除数据
     * <br>Created 2014-7-27 下午7:49:13
     * @author       cb
    */
    public void clearData(){
    	for (IMessageDisplay msg : mMessageList) {
    		ArrayList<Object> list=msg.getDisplayDatas();
    		list.clear();
    	}
    	mMessageList.clear();
        mChatAdapter.setList(mMessageList);
    	unregistObserver();
    }
    
    /**
     * 滚动到底不
     * 
     * <br>Created 2014-11-26 下午6:50:39
     * @param isDoJudge 是否执行判断
     * @author        :  HuangYK
     */
	public void scrollToBottom(boolean isDoJudge) {
		if (isDoJudge
				&& mListView.getLastVisiblePosition() != mMessageList.size()) {
			return;
		}
		if (mListView != null && mMessageList != null) {
			mListView.setSelection(mMessageList.size());
		}
	}
	
	/**
	 * 刷新界面资料显示(昵称，头像)
	 * 
	 * <br>Created 2014-12-15 下午7:26:30
	 * @author       ChuXY
	 */
	public void refreshChatItemShow() {
		mChatAdapter.setIsNotify(true);
		mChatAdapter.notifyDataSetChanged();
	}
}
